package jdbc;/*
 *
 * @author 陈粒
 * @version 创建时间：2021/8/4 10:33
 */

import util.JDBCutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBC_Affair {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstm1 = null;
        PreparedStatement pstm2 = null;
        try {
            //获取连接对象
            conn = JDBCutils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //执行sql
            String sql1 = "UPDATE salary set salary = salary - ? WHERE id=?";
            String sql2 = "UPDATE salary set salary = salary + ? WHERE id=?";
            pstm1 = conn.prepareStatement(sql1);
            pstm2 = conn.prepareStatement(sql2);
            pstm1.setInt(1, 100);
            pstm1.setInt(2, 1);
            pstm2.setInt(1, 100);
            pstm2.setInt(2, 2);
            pstm1.executeUpdate();
            int i = 3 / 0;//主动出错
            pstm2.executeUpdate();
            //提交事务
            conn.commit();
        } catch (Exception e) {
            //回滚事务
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCutils.close(pstm1, pstm2, conn);
        }
    }
}
